package com.jsmile.cloud.authc.sys.repo;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsmile.cloud.authc.sys.dao.SysRoleDao;
import com.jsmile.cloud.authc.sys.model.SysRole;
import com.jsmile.cloud.authc.sys.model.SysRoleResources;
import com.jsmile.cloud.authc.sys.model.SysUserRole;

import lombok.extern.slf4j.Slf4j;

/**
 * @author 龚亮
 * @version 1.0
 * @desc 为了薪资破万，还是睡一会儿吧...!
 * @date 2020年10月16日 02:46:20
 */
@Service
@Slf4j
@Transactional(readOnly = false, rollbackFor = Exception.class)
public class SysRoleRepository extends ServiceImpl<SysRoleDao, SysRole> {

    public boolean deleteRoles(List<Long> roleIds) {
        for (int i = 0; i < roleIds.size(); i++) {
            this.baseMapper.deleteRoleResource(roleIds.get(i));
        }
        return retBool(this.baseMapper.deleteBatchIds(roleIds));
    }

    /**
     * desc: 添加角色权限
     */
    public boolean saveRoleResources(Long roleId, List<Long> resourceIds) {
        int i = this.baseMapper.deleteRoleResource(roleId);
        if (resourceIds != null && resourceIds.size() > 0) {
            for (Long resourceId : resourceIds) {
                SysRoleResources rr = new SysRoleResources();
                rr.setResourcesId(resourceId);
                rr.setRoleId(roleId);
                i += this.baseMapper.saveRoleResources(rr);
            }
        }
        return retBool(i);
    }

    public boolean saveUserRole(Long userId, List<Long> roleIds, Long tenantId) {
        int i = this.baseMapper.deleteUserRole(userId);
        if (roleIds != null && roleIds.size() > 0) {
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                ur.setTenantId(tenantId);
                i += this.baseMapper.saveUserRole(ur);
            }
        }
        return retBool(i);
    }
}
